<?php

class Helper extends CController {

    public static function utf_substr($string, $length, $etc = '...') {
        $result = '';
        $string = html_entity_decode(trim(strip_tags($string)), ENT_QUOTES, 'UTF-8');
        $strlen = strlen($string);
        for ($i = 0; (($i < $strlen) && ($length > 0)); $i++) {
            if ($number = strpos(str_pad(decbin(ord(substr($string, $i, 1))), 8, '0', STR_PAD_LEFT), '0')) {
                if ($length < 1.0) {
                    break;
                }
                $result .= substr($string, $i, $number);
                $length -= 1.0;
                $i += $number - 1;
            } else {
                $result .= substr($string, $i, 1);
                $length -= 0.5;
            }
        }
        $result = htmlspecialchars($result, ENT_QUOTES, 'UTF-8');
        if ($i < $strlen) {
            $result .= $etc;
        }
        return CHtml::encode($result);
    }

    /*
     * @todo 生成随机码
     */

    public static function randCode($mobile='',$length = 6,$category ='verifyCode.') {
        //$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%';

        if(false!=($data=Yii::app()->cache2->get($category.$mobile)))
        {
            $randpwd = $data;
        }
        else
        {
            $chars = '0123456789';
            $randpwd = '';
            for ($i = 0; $i < $length; $i++) {
                $randpwd .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            }
            $sess = Yii::app()->session;
            $sess['mobileCode'] = $randpwd;
            Yii::app()->cache2->set($category.$mobile,$randpwd,600);
        }
        return $randpwd;
    }
    /**
     * 获取保存在redis里的随机码（短信发送给用户的验证码）
     */
    public static function  getCode($mobile,$category= 'verifyCode.')
    {
        return Yii::app()->cache2->get($category.$mobile);
    }

    /*
     * @todo 验证手机号码
     */

    public static function checkMobile($mobile) {
        return preg_match("/^1[3|4|5|8][0-9]{9}$/", $mobile);
    }

    public static function strim($data) {
        if (!is_array($data))
            return false;
        $return = array();
        foreach ($data as $key => $value) {
            $return[$key] = trim($value);
        }
        return $return;
    }

    public static function number2Chinese($num, $m = 1) {
        switch ($m) {
            case 0:
                $CNum = array(
                    array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'),
                    array('', '拾', '佰', '仟'),
                    array('', '萬', '億', '萬億')
                );
                break;
            default:
                $CNum = array(
                    array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九'),
                    array('', '十', '百', '千'),
                    array('', '万', '亿', '万亿')
                );
                break;
        }
// $cNum = array('零','一','二','三','四','五','六','七','八','九');

        if (is_integer($num)) {
            $int = (string) $num;
        } else if (is_numeric($num)) {
            $num = explode('.', (string) floatval($num));
            $int = $num[0];
            $fl = isset($num[1]) ? $num[1] : FALSE;
        }
// 长度
        $len = strlen($int);
// 中文
        $chinese = array();

// 反转的数字
        $str = strrev($int);
        for ($i = 0; $i < $len; $i+=4) {
            $s = array(0 => $str[$i], 1 => $str[$i + 1], 2 => $str[$i + 2], 3 => $str[$i + 3]);
            $j = '';
// 千位
            if ($s[3] !== '') {
                $s[3] = (int) $s[3];
                if ($s[3] !== 0) {
                    $j .= $CNum[0][$s[3]] . $CNum[1][3];
                } else {
                    if ($s[2] != 0 || $s[1] != 0 || $s[0] != 0) {
                        $j .= $CNum[0][0];
                    }
                }
            }
// 百位
            if ($s[2] !== '') {
                $s[2] = (int) $s[2];
                if ($s[2] !== 0) {
                    $j .= $CNum[0][$s[2]] . $CNum[1][2];
                } else {
                    if ($s[3] != 0 && ($s[1] != 0 || $s[0] != 0)) {
                        $j .= $CNum[0][0];
                    }
                }
            }
// 十位
            if ($s[1] !== '') {
                $s[1] = (int) $s[1];
                if ($s[1] !== 0) {
                    $j .= $CNum[0][$s[1]] . $CNum[1][1];
                } else {
                    if ($s[0] != 0 && $s[2] != 0) {
                        $j .= $CNum[0][$s[1]];
                    }
                }
            }
// 个位
            if ($s[0] !== '') {
                $s[0] = (int) $s[0];
                if ($s[0] !== 0) {
                    $j .= $CNum[0][$s[0]] . $CNum[1][0];
                } else {
// $j .= $CNum[0][0];
                }
            }
            $j.=$CNum[2][$i / 4];
            array_unshift($chinese, $j);
        }
        $chs = implode('', $chinese);
        if ($fl) {
            $chs .= '点';
            for ($i = 0, $j = strlen($fl); $i < $j; $i++) {
                $t = (int) $fl[$i];
                $chs.= $str[0][$t];
            }
        }
        return $chs;
    }
    public static function mb_substr_replace($string,$replacement,$start,$length=null,$encoding = 'utf-8')
    {
        if($string=='')
            return '';
        if ($encoding == null){
            if ($length == null){
                return mb_substr($string,0,$start).$replacement;
            }
            else{
                return mb_substr($string,0,$start).$replacement.mb_substr($string,$start + $length);
            }
        }
        else{
            if ($length == null){
                return mb_substr($string,0,$start,$encoding).$replacement;
            }
            else{
                return mb_substr($string,0,$start,$encoding). $replacement. mb_substr($string,$start + $length,mb_strlen($string,$encoding),$encoding);
            }
        }
    }
    /**
     * 星号替代
     * @param $value
     * @param string $star
     * @param int $begin
     * @param int $length
     * @return string
     */
    public static function startReplace($value,$star='*',$begin=0,$length=4)
    {
        return ($value=='')?false:Helper::mb_substr_replace($value,str_repeat($star,$length),$begin,$length);
    }


     public static function getTradeUUID($gateWayId,$userId='')
    {
        //CG_RECHARGE+时间戳+用户ID+第三方标识
        if(!$gateWayId || !isset(Yii::app()->params['recharge']['gateWay'][$gateWayId]) || !$userId)
        {
            echo json_encode(array(
                'success' => 0,
                'msg'     => 'gateway invalid,please try angin later',
            ));
        }
        $userId       = substr($userId,6,6);
        $aRecharge    = Yii::app()->params['recharge'];
        $rechargeMark = RECHARGEMARK.$aRecharge['mark'];
        return $rechargeMark.'_'.time().$userId.$aRecharge["gateWay"][$gateWayId]['name'];
    }
    public static function listOptions($data,$value,$name)
    {
        $tmp = array();
        if(is_array($data))
        {
            foreach ($data as $v) {
                $tmp[$v->$value]=$v->$name;
            }
        }
        return $tmp;
    }
    //通过curl获取url内容
    public static function get_curl_contents($url, $second = 30)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);//false时,curl_exec($ch)返回的是true/false

        //以下两项设置为FALSE时,$url可以为"https://login.yahoo.com"协议
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  FALSE);

        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
    /**
     * 根据银行来优先选择是绑定连连还是绑定联动优势
     * return 0;两者都不能用
     *        LL:选择连连
     *        UMP: 选择联动优势
     *        NOT_SUPPORT:银行卡不支持
     */
    public  static function  chooseChannel($bank_id)
    {
        $banks = self::getAvailableBanks();
        if($banks === array())
        {
            return 0;//两个支付通道都不能用
        }
        $support = false;
        $channel = 'LL';
        foreach($banks as $bank)
        {
            if($bank['code'] == $bank_id)
            {
                $support = true;
                $channel = $bank['priority'];
            }
        }
        if(!$support)
            return 'NOT_SUPPORT';
        return $channel;
    }
    /**
     * 获取可用的银行
     * @param  string $avaliableChannel [description]
     * @return [type]                   [description]
     */
    public static function getAvailableBanks()
    {
        $availableBanks = array();
        if(Yii::app()->cache2->get('pay_ll_closed'))
        {
            $availableBanks = array();
        }
        else
        {
            $config = Yii::app()->cache2->get('withdrawChannal');
            if($config)
            {
                $config = json_decode($config);
                $banks  = Yii::app()->cache_php->lrange('llSupportedBanks',0,-1);
                if($config->channel == 'sp')
                {
                    if($banks)
                    {
                        foreach($banks as $bank)
                        {
                            $bank = json_decode($bank);
                            $availableBanks[] = array(
                                'code'        => $bank->code,
                                'name'        => $bank->name,
                                'alias'       => $bank->alias,
                                'needBranch'  => $bank->needBranch,
                                'singleLimit' => $bank->singleLimit,
                                'pay_limit'   => $bank->singleLimit,
                                'dayLimit'    => $bank->dayLimit,
                                'monthLimit'  => $bank->monthLimit,
                            );
                        }
                    }
                }
                else
                {
                    if($banks)
                    {
                        foreach($banks as $bank)
                        {
                            $bank = json_decode($bank);
                            $availableBanks[] = array(
                                'code'        => $bank->code,
                                'name'        => $bank->name,
                                'alias'       => $bank->alias,
                                'needBranch'  => in_array($bank->code, array(3,8,9,12,14))?1:0,
                                'singleLimit' => $bank->singleLimit,
                                'pay_limit'   => $bank->singleLimit,
                                'dayLimit'    => $bank->dayLimit,
                                'monthLimit'  => $bank->monthLimit,
                            );
                        }
                    }
                }
            }
        }
        return $availableBanks;
    }
    /**
     * 获取银行单笔限额
     * @param  [type] $bank_id [description]
     * @param  [type] $pay_method [ 支付通道: 3(连连) 或者 5(联动)]
     * @return [type]          [description]
     */
     public static function getBankPayLimit($bank_id,$pay_method)
    {
        if($pay_method != 3)
        {
            echo json_encode(array(
                'success' => 0,
                'msg'     => '支付通道不正确',
            ));
            Yii::app()->end();
        }
        $banks = Yii::app()->params['mobileBanks'];
        foreach($banks as $bank)
        {
            if($bank['code']==$bank_id)
            {
                return $bank['singleLlLimit'];
            }
        }
    }
    /**
     * 获取bank_code
     */
    public static function getBankCode($bank_id)
    {
        $banks = Yii::app()->cache_php->lrange('llSupportedBanks',0,-1);
        if($banks)
        {
            foreach($banks as $bank)
            {
                $bank = json_decode($bank);
                if($bank->code == $bank_id)
                    return $bank->alias;
            }
        }
        return '';
    }
    /**
     * 格式化数据
     * @param  [type]  $number        [description]
     * @param  integer $decimals      [description]
     * @param  boolean $she           是否舍去零头 默认四舍五入
     * @param  string  $dec_point     [description]
     * @param  string  $thousands_sep [description]
     * @return [type]                 [description]
     */
    public static function formatNumber($number,$decimals = 0,$she=false,$dec_point = ".", $thousands_sep = "")
    {
        if($she)
        {
            $times = pow(10,$decimals);
            $number = bcmul($number,$times)/$times;
        }
        return number_format($number,$decimals,$dec_point,$thousands_sep);
    }
    /**
     * 连连签名
     * is_recharge: 0:订单签名 1：绑卡签名 2：充值签名
     * @return [type] [description]
     */
    public static function llSign($p,$is_recharge=0)
    {
        Yii::trace('传递 参数'.json_encode($p));
        $return = array('success'=>0,'msg'=>' ');
        if($p['bind_card'])//如果是绑卡的话 则校验身份证是否被别人绑定
        {
            $model = User::model();
            $check = $model->checkNameIdentity($p['user_id'],$p['name'],$p['identity']);
            if($check['success'] !==1)
            {
                $return['msg'] = $check['msg'];
                return $return;
            }
        }
        $llpay_config = Yii::app()->params['llpay'];
        $service_name = "orderForm";//固定值
        $name_goods   = "草根投资充值";//商品名称
        $info_order   = "草根投资充值";//订单描述
        $dt_order     = date('YmdHis', time());//商户订单时间
        $user         = User::model();
        $bank_id      = $p['bank_id'];
        $card_number  = $p['card_number'];
        $params = array(
            'service_name'   => $service_name,
            'busi_partner'   => $llpay_config['busi_partner'],
            'no_order'       => $p['no_order'],
            'dt_order'       => $dt_order,
            'money_order'    => $p['money_order'],//交易金额  精确到小数点后两位
            'notify_url'     => $llpay_config['notify_url'],
            'name_goods'     => $name_goods,
            //  'info_order' => $info_order,
            'sign_type'      => 'MD5',
            'oid_partner'    => $llpay_config['oid_partner'],
            'valid_order'    => '',
            'risk_item'      => '',
            'user_id'        => $p['user_id'],
            'bank_id'        => $bank_id,
            'card_no'        => $card_number,
            'is_recharge'    => $is_recharge,
            'name'           => $p['name'],
            'identity'       => $p['identity'],
        );
        Yii::trace('获取签名 参数'.json_encode($params));
        $result = HttpLib::post(Yii::app()->params['scripts']['lianlian_sign'],$params);
        if($result->success)
        {
            $return['msg']            = 'ok';
            $return['success']        = 1;
            $return['notifyUrl']      = $result->result->notifyUrl;
            $return['sign']           = $result->result->sign;
            $info                     = $user->findById($p['user_id']);
            $return['name']           = $p['name'];
            $return['identity']       = $p['identity'];
            $return['no_order']       = $p['no_order'];
            $return['dt_order']       = $dt_order;
            $return['bank_tip']       = '提示：建设银行于22:00-24:00数据维护，暂停支付服务';
            if(!$p['bind_card'])
            {
                $return['no_agree']       = '';
                $return['starName']       = $info->starName;
                $return['starIdentity']   = $info->starIdentity;
                $return['bank_id']        = $bank_id;
                $return['card_number']    = $card_number;
                $return['starCardNumber'] = mb_substr($card_number, 0,4).' **** **** '.mb_substr($card_number,-4);
                //获取协议号
                $b = User::model()->getBankCard($p['user_id']);
                if($b[0] && $b[0]['protocolNo'])
                    $return['no_agree'] = $b[0]['protocolNo'];
                else
                {
                    $remote = HttpLib::get(Yii::app()->params['scripts']['ll_user_cards'],array('user_id'=>$p['user_id'],'card_no'=>$card_number));
                    if($remote->success && $remote->result->ret_code != 8901)
                    {
                        $return['no_agree'] = $remote->result[0]->no_agree?$remote->result[0]->no_agree:'';
                    }
                }
                $return['no_agree_status'] = $return['no_agree']?1:0;
            }
            Yii::trace('签名结果'.json_encode($return));
        }
        else
        {
            $return['msg'] = $result->errorMsg;
            Yii::log('签名失败 原因'.$result->errorMsg,'error');
        }
        return $return;
    }
    /**
     * 获取银行卡单笔最大支付额度
     * @param  [type] $bank_id    [description]
     * @param  [type] $pay_method [description]
     * @return [type]             [description]
     */
    public static function getMaxPayAmount($bank_id,$pay_method)
    {
        if(!in_array($pay_method, array(3,5)))
        {
            echo json_encode(array(
                'success' => 0,
                'msg'     => 'pay_method not support',
            ));
            Yii::app()->end();
        }
        $channel = 'LL';
        if($pay_method==5)
            $channel = 'UMP';
        $banks = Yii::app()->params['mobileBanks'];
        foreach($banks as $bank)
        {
            if($bank_id == $bank['code'])
            {
                if($channel=='LL')
                    return $bank['singleLlLimit'];
                return $bank['singleUmpLimit'];
            }
        }
    }
     /**
     * 把ios的ifa推送到一个队列里
     */
    public static function pushIFA($mobile,$category,$amount=0)
    {
        $p = array(
            'ip'         => HttpLib::getRemoteIp(),
            'appversion' => APPVERSION,
            'ifa'        => DEVICESERIALID,
            'mobile'     => md5($mobile),
            'mobile2'    => $mobile,
            'where'      => $category,
            'time'       => time(),
            'amount'     => $amount,
        );
        Yii::app()->cache_php->lpush('app_ios_ad',json_encode($p));
        // Yii::trace('ios ifa info'.json_encode($p));
    }

    /*
     * 返回溢价额
     */
    public static function getPremium($model, $amount)
    {
        $tmp = $model->projectInterestList;
        foreach ($tmp as $v) {
            if ($amount >= $v->minInvest && $amount < $v->maxInvest) {
                return $v->premiumAmount;
            } elseif ($amount == $v->maxInvest) {
                return $v->premiumAmount;
            }
        }
        return 0;
    }

    /*
     * 原债价值+收益，即合同里 X值
     * @param object $model
     * @param int    $amount
    */
    public static function debtValue($interest, $amount)
    {
        if ($interest->result) {
            return round($amount + $interest->result->totalIncome, 2);
        }
        return $amount;
    }

    /**
     * 记录经纬度
     */
    public static function positionRecord($where='init',$user_id='')
    {
        $longitude = $_REQUEST['longitude']?floatval($_REQUEST['longitude']):'';//经度
        $latitude  = $_REQUEST['latitude']?floatval($_REQUEST['latitude']):'';//纬度
        if($longitude || $latitude)
        {
            Yii::app()->cache_php->lpush('CGTZ_APP_POSITION',json_encode(array(
                'version'   => APPVERSION,
                'os'        => MOBILEOS,
                'ifa'       => DEVICESERIALID,
                'time'      => time(),
                'where'     => $where,
                'longitude' => $longitude,
                'latitude'  => $latitude,
                'user_id'   => $user_id,
            )));
        }
    }

    public static function getPraise($user_id)
    {
        $cache = Yii::app()->cache_php;
        $praise = 0;
        if(MOBILEOS==='ios' && DEVICESERIALID && !$cache->exists($user_id.DEVICESERIALID))
        {
            $praise = 1;
            Yii::app()->cache_php->set($user_id.DEVICESERIALID,1);
        }
        return $praise;
    }
    /** 
     * 校验是否简单密码
     */
    public static function checkIsSimplePass($password)
    {
        $simples = self::generateSimpleMD5Passwords();
        if(in_array($password, $simples))
            return true;
        return false;
    }
    /**
     * 生成简单密码
     */
    public static function generateSimpleMD5Passwords()
    {
        $passwords   = Yii::app()->cache_php->get('singlePasswords');
        if($passwords)
            $passwords = (array)json_decode($passwords);
        else
        {
            $passwords    = array();
            $singles = array(0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z);
            foreach($singles as $v)
            {
                for($i=6;$i<=20;$i++)
                {
                    $k = str_repeat($v, $i);
                    $passwords[$k] = md5($k);
                }
            }
            $lians    = array(
                '0123456789',
                '9876543210',
            );
            foreach($lians as $n)
            {
                for($i=0;$i<=4;$i++)
                {
                    $length = 10-$i;
                    for($j=6;$j<=$length;$j++)
                    {
                        $k = substr($n, $i,$j);
                        $passwords[$k] = md5($k);
                    }
                }
            }
            Yii::app()->cache_php->set('singlePasswords',json_encode($passwords));
        }
        return $passwords;
    }
    /**
     * 记录耗时时间较长的请求
     */
    public static function recordPerformanceLog($seconds,$content)
    {
        if($seconds > 100)
        {
            Yii::log($content,'info','api.performance.info');
        }
    }
}